package com.fan.springboot.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.fan.springboot.domain.News;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

@Repository
public class NewsDao {

	@Autowired
	private MongoTemplate mongoTemplate;

	public void save(News news) {
		news.setCreateTime(new Date().getTime());
		news.setUpdateTime(new Date().getTime());
		mongoTemplate.save(news);
	}

	public void delete(String id) {
		mongoTemplate.remove(new Query(Criteria.where("id").is(id)), News.class);
	}

	public void update(News news) {
		Query query = new Query(Criteria.where("id").is(news.getId()));
		Update update = new Update().set("fileName", news.getFileName()).set("filePath", news.getFilePath())
				.set("completePath", news.getCompletePath()).set("title", news.getTitle())
				.set("summary", news.getSummary()).set("content", news.getContent())
				.set("updateTime", new Date().getTime()).set("contentPictures", news.getContentPictures());
		mongoTemplate.updateFirst(query, update, News.class);
	}

	public Object findAllbyDESC(int currentPage, int limitNumber) {
		List<News> newsList = null;
		long totalCount = 0; // 总记录数

		try {
			DBObject dbObject = new BasicDBObject();
			BasicDBObject fieldsObject = new BasicDBObject();
			// 指定返回的字段
			fieldsObject.put("content", false);
			Query query = new BasicQuery(dbObject, fieldsObject);
			query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "createTime")))
					.skip((currentPage - 1) * limitNumber).limit(limitNumber);
			newsList = mongoTemplate.find(query, News.class);
			totalCount = mongoTemplate.count(query, News.class);

		} catch (Exception e) {
			e.printStackTrace();
		}

		Map<String, Object> map = new HashMap<>();
		map.put("newsList", newsList);
		map.put("totalCount", totalCount);

		return map;
	}

	// 根据id获取项目
	public News getNewsById(String id) {
		return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)), News.class);
	}

}
